<template>
  <div>
    <el-dialog
      :close-on-click-modal="false"
      :beforeClose="handleClose2"
      title="采购排货"
      :visible.sync="dialogVisible2"
      width="800px">

      <el-form :model="sendForm" size="mini" label-width="120px"  ref="sendForm" :rules="rules2">
          <el-form-item label="采购合同类型：" prop="orderType">
              <el-radio-group v-model="sendForm.orderType" @click="changeOrderType">
                <el-radio label="purchaseOrder">采购合同</el-radio>
                <el-radio label="agentProcess">代加工单</el-radio>
                <el-radio label="other">其它</el-radio>
              </el-radio-group>
          </el-form-item>
          <el-form-item label="采购合同单号："  v-if="sendForm.orderType != 'other'" prop="orderId">
            <el-select
              clearable
              @change="changeOrderId"
              v-model="sendForm.orderId"
              filterable
              remote
              placeholder="请输入供应商名称/合同号"
              :remote-method="((val)=>{remoteMethod3(val)})"
              :loading="orderLoading">
              <el-option :value="item.orderId"
                         :label="item.orderSn+'/'+item.supplierName+'/'+item.goodsName+'/'+item.goodsSn+'/'+item.goodsNum+'吨/可提'+item.unTakeNum+'吨'"
                         v-for="(item,index) in purchaseOrderList" :key="index"></el-option>
            </el-select>
            <span style="padding-left:10px;font-size:12px;color:#888">付款完成且未提数量大于0的采购合同</span>
          </el-form-item>

          <el-form-item label="供应商：" prop="supplierName">
                <el-autocomplete
                  clearable
                  class="inline-input"
                  value-key="supplierName"
                  :fetch-suggestions="querySearch"
                  v-model="sendForm.supplierName"
                  placeholder="请输入内容"
                  @select="handleSelectSupplierName"
                  :trigger-on-focus="false"
                ></el-autocomplete>
          </el-form-item>
          <el-form-item label="合同公司：" prop="fromCompany">
              <el-select v-model="sendForm.fromCompany">
                  <el-option value="常州普利成" label="常州普利成" key="常州普利成"></el-option>
                  <el-option value="塑盟科技集团有限公司" label="塑盟科技集团有限公司" key="塑盟科技集团有限公司"></el-option>
                  <el-option value="上海泛塑" label="上海泛塑" key="上海泛塑"></el-option>
                <el-option value="华灯车尚" label="华灯车尚" key="华灯车尚"></el-option>
              </el-select>
          </el-form-item>

          <el-form-item label="提货时间：" prop="takeTime">
              <el-date-picker
                      :picker-options="pickerOptions"
                      value-format="yyyy-MM-dd"
                      v-model="sendForm.takeTime"
                      style="display: inline-block;width:150px"
                      type="date"
                      placeholder="选择日期">
              </el-date-picker>
          </el-form-item>
          <el-form-item label="提货概率：" prop="isSure">
            <el-radio-group v-model="sendForm.isSure">
              <el-radio :label="1">确定<span style="color:#999;padding-left:5px">(保证准时发货)</span></el-radio>
              <el-radio :label="0">不确定</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="提货类型：" prop="planSendType" >
              <el-radio-group v-model="sendForm.planSendType">
                  <el-radio label="运联发货">运联发货</el-radio>
              </el-radio-group>
          </el-form-item>
          <el-form-item label="提货商品：" >
              <el-table :data="sendForm.detailData" border style="width: 100%;margin:20px 0">
                  <el-table-column
                          align="center"
                          label="商品名称"
                          width="200">
                      <template slot-scope="scope">
                           <div v-if="sendForm.orderId == ''">
                             <el-form-item :prop="`detailData.${scope.$index}.goodsKingId`" :rules="rules2.goodsKingId" >
                               <el-select
                                 @change="changeGoods(scope.row.kingGoodsId,scope.$index)"
                                 v-model="scope.row.goodsKingId"
                                 filterable
                                 remote
                                 placeholder="请输入关键词"
                                 :remote-method="((val)=>{remoteMethod(val)})"
                                 :loading="goodsLoading">
                                 <el-option
                                   v-for="item in list"
                                   :key="item.kingGoodsId"
                                   :label="item | fifitem"
                                   :value="item.kingGoodsId">
                                 </el-option>
                               </el-select>
                             </el-form-item>

                           </div>
                          <div v-else>{{scope.row.goodsName}} / {{scope.row.goodsSn}}</div>
                      </template>
                  </el-table-column>
                  <el-table-column
                          v-if="sendForm.orderId != ''"
                          label="采购数量"
                          width="100"
                          align="center">
                      <template slot-scope="scope">
                        {{ scope.row.goodsNum }}吨
                      </template>
                  </el-table-column>
                  <el-table-column
                          width="150"
                          align="center"
                          label="包装">
                      <template slot-scope="scope">
                         <el-form-item :prop="`detailData.${scope.$index}.goodsWeight`" :rules="rules2.goodsWeight" >
                           <el-input style="width:80px" v-model="scope.row.goodsWeight"></el-input><span style="padding-left:5px">kg/包</span>
                         </el-form-item>
                      </template>
                  </el-table-column>
                  <el-table-column
                          label="提货数量（吨）"
                          width="120"
                          align="center">
                      <template slot-scope="scope">
                        <el-form-item :prop="`detailData.${scope.$index}.planNum`" :rules="rules2.planNum" >
                          <el-input v-model="scope.row.planNum"></el-input>
                        </el-form-item>
                      </template>
                  </el-table-column>
                  <el-table-column  label="是否含托" width="100" align="center">
                      <template slot-scope="scope">
                          <el-checkbox v-model="scope.row.isHasTray">是</el-checkbox>
                      </template>
                  </el-table-column>
                  <el-table-column  label="备注" width="100" align="center">
                      <template slot-scope="scope">
                        <el-form-item>
                          <el-input v-model="scope.row.goodsRemark"></el-input>
                        </el-form-item>
                      </template>
                  </el-table-column>
                  <el-table-column  label="操作" width="100" align="center" fixed="right">
                      <template slot-scope="scope">
                          <el-button type="text" @click="delGoods(scope.$index)">删除</el-button>
                      </template>
                  </el-table-column>
              </el-table>
              <el-button type="primary" size="small" @click="addGoods" v-if="sendForm.orderId == ''">增加商品</el-button>
          </el-form-item>

          <el-form-item label="仓库：" prop="takeWarehouse">
              <el-select
                      style="width:250px;display: inline-block"
                      clearable
                      v-model="sendForm.takeWarehouse"
                      filterable
                      remote
                      reserve-keyword
                      placeholder="请输入关键词"
                      @change="changeWarehouseId"
                      :remote-method="remoteMethod2"
                      :loading="loading2">
                  <el-option
                          v-for="item in options2"
                          :key="item.warehouseId"
                          :label="item.warehouseName+' / '+item.warehouseAddress"
                          :value="item.warehouseName">
                  </el-option>
              </el-select>
            <el-button type="text" style="display: inline-block" @click="showDialog5">增加仓库</el-button>
          </el-form-item>

          <el-form-item label="联系人："  prop="contactName" >
              <el-input v-model="sendForm.contactName"  style="width:200px"></el-input>
          </el-form-item>
          <el-form-item label="手机号："  prop="contactMobile">
              <el-input v-model="sendForm.contactMobile" style="width:200px"></el-input>
          </el-form-item>
          <el-form-item label="联系地址："  prop="takeAddress">
              <el-input v-model="sendForm.takeAddress"></el-input>
          </el-form-item>
          <el-form-item label="仓库注意事项：" >
              <el-input :autosize="{ minRows: 2, maxRows: 6}" type="textarea" v-model="sendForm.takeNote"></el-input>
          </el-form-item>
          <el-form-item label="提货备注：" >
              <el-input :autosize="{ minRows: 2, maxRows: 6}" type="textarea" v-model="sendForm.takeRemark"></el-input>
              <div>
                <el-checkbox v-if="sendForm.planSendType == '运联发货'"  v-model="sendForm.isNeedDriverUnload">司机卸货</el-checkbox>
              </div>
          </el-form-item>

          <el-form-item label="收货信息：" prop="warehouseId">
            <el-radio-group v-model="sendForm.warehouseId" @change="changeSHWarehouseId">
              <el-radio :label="item.warehouseId" v-for="item in shckList" :key="item.warehouseId">{{item.warehouseName}}</el-radio>
            </el-radio-group>
            <div>
              <el-form-item label="地址填写：" v-if="sendForm.warehouseId==1151&&sendForm.orderType=='other'" label-width="80px">
                <el-input v-model="sendForm.receiveAddress" clearable></el-input>
              </el-form-item>
              <div v-else>{{ curShWarehouse.contactName }} / {{ curShWarehouse.contactMobile }} / {{ curShWarehouse.warehouseAddress }}</div>
            </div>
          </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
          <el-button @click="handleClose2">取 消</el-button>
          <el-button type="primary" @click="handleConfirm2" :loading="btnLoading2">确 定</el-button>
      </span>
    </el-dialog>

    <!--增加仓库-->
    <warehouseInfo ref="warehouseInfo" @getList="getWarehouseList"></warehouseInfo>


  </div>
</template>
<script>
import "@/utils/jQuery.print"
import {supplierList,getCrmGoodsList} from '@/api/partner'
import {warehouseListPlan,purchaseGoodsDetail,suggestOrderSn,planPurchaseGoods} from '@/api/order'
import warehouseInfo from "./warehouseInfo.vue"
const defaultSendForm={
  "orderType" : "purchaseOrder", //订单类型(采购单-purchaseOrder,代加工单-agentProcess,其它-other)
  "supplierName"  : "", //供应商ID
  "fromCompany" : "",  //合同公司
  "takeTime" : "", //提货时间
  "isSure" : 1, //提货概率(0不确定，1确定)
  "planSendType" : "运联发货",  //提货类型:工厂发货、运联发货、自提
  "detailData" : [],  //排货的商品信息
  "takeWarehouse" : "", //提货仓库
  "contactName" : "", //联系人
  "contactMobile" : "", //联系人手机号
  "takeAddress" : "",  //提货地址
  "takeRemark" : "原厂正牌，原料生产日期不超过合同签订日前六个月，外观无破损、潮湿，无大面积污渍，包装袋规格及颜色一致。", //提货备注
  "takeNote" : "", //注意事项
  "driverName" : "", //司机姓名
  "driverMobile" : "", //司机手机号
  "driverTruckNo" : "", //司机车牌号
  "isNeedDriverUnload" : '', //是否需要司机卸货(0不需要，1需要)
  "warehouseId" : '', //收货仓库ID
  orderId: '',
  receiveAddress:'',
};

export default {
  name: "printdischarging",
  data(){
    const isvalidatePurchaseOrderId = (rule, value, callback) => {
      if(this.sendForm.orderType == 'purchaseOrder' && value == '' ){
        callback(new Error('请关联采购合同'))
      } else {
        callback()
      }
    };
    return {
      dialogVisible2:false,
      rules2:{
        supplierName:[{required: true, message: '请输入供应商', trigger: 'blur'},],
        fromCompany:[{required: true, message: '请选择合同公司', trigger: 'change'},],
        takeWarehouse   :[{required: true, message: '请选择仓库', trigger: 'change'},],
        contactName   : [{required: true, message: '请输入联系人', trigger: 'blur'},],
        contactMobile : [{required: true, message: '请输入联系人手机号', trigger: 'blur'},],
        takeAddress   : [{required: true, message: '请输入提货地址', trigger: 'blur'},],
        takeTime      : [{required: true, message: '请输入提货时间', trigger: 'blur'},],
        planSendType      : [{required: true, message: '请选择提货类型', trigger: 'change'},],
        goodsWeight: [{required: true, message: '请输入商品包装', trigger: 'blur'},],
        goodsKingId:[{required: true, message: '请选择商品', trigger: 'change'},],
        isSure:[{required: true, message: '请选择提货概率', trigger: 'change'},],
        planNum:[{required: true, message: '请输入提货数量', trigger: 'blur'},],
        warehouseId:[{required: true, message: '请选择收货仓库', trigger: 'change'},],
        orderId:[{required: true, validator:isvalidatePurchaseOrderId, trigger: 'change'},],
      },
      btnLoading2:false,
      sendForm:JSON.parse(JSON.stringify(defaultSendForm)),

      options2:[],
      pickerOptions: {
        disabledDate(time) {
          return time.getTime() < Date.now() - 8.64e7
        }
      },

      cutItem:{},
      purchaseOrderList:[],
      curWarehouse:{},
      listLoading:false,
      loading:false,
      options3:[],
      list:[],
      goodsLoading:false,
      shckList:[],
      orderLoading:false,
      loading2:false,
      curShWarehouse:{},

    }
  },

  components : {
    warehouseInfo:warehouseInfo
  },

  filters: {
    fifitem(item){
      return item.goodsName+'/'+item.goodsSn
    },
  },

  created() {


  },

  methods:{
    //供应商名称输入匹配
    querySearch(queryString, cb){
      supplierList({supplierName:queryString}).then((res)=>{
        cb(res);
      })
    },

    //选择供应商名称
    handleSelectSupplierName(item){
      this.sendForm.supplierName = item.supplierName
    },
    // 切换采购合同类型
    changeOrderType() {
      this.curShWarehouse = JSON.parse(JSON.stringify(curWarehouse));
      this.sendForm.receiveAddress = '';
    },

    //切换收货仓库
    changeSHWarehouseId(val){
      let curWarehouse = this.shckList.find((el)=>{
        return el.warehouseId == val
      });
      this.curShWarehouse = JSON.parse(JSON.stringify(curWarehouse));
      this.sendForm.receiveAddress = '';
    },
      //获取收货仓库列表
      getShckList (){
        warehouseListPlan({isSelfBusiness:1}).then((res)=>{
          this.shckList = res;
          this.sendForm.warehouseId = this.shckList[0] ? this.shckList[0]['warehouseId']:'';
          this.curShWarehouse =  this.shckList[0] ? this.shckList[0] : {};
        })
      },

      //联想商品
      remoteMethod(key){
        this.goodsLoading = true;
        getCrmGoodsList({keyword:key}).then((res)=>{
          this.list = res;
          this.goodsLoading = false;
        }).catch(()=>{
          this.goodsLoading = false;
        })
      },

      //切换商品
      changeGoods(kingGoodsId,index){
        // let c = {};
        // c = this.list.find((el)=>{
        //   return el.kingGoodsId == kingGoodsId;
        // });
        // this.sendForm.kingGoodsId = c.kingGoodsId;
        // this.sendForm.goodsName = c.goodsName;
        // this.sendForm.goodsSn = c.goodsSn;
      },
      delGoods(index){
        this.sendForm.detailData.splice(index,1)
      },
      addGoods(){
          this.sendForm.detailData.push({
              goodsKingId:'',
              goodsWeight:'',
              planNum:'',
              isHasTray:false,
              goodsRemark:'',
          })
      },

      //供应商
      getSupplierList() {
          supplierList().then((res)=>{
              this.options3 = res;
          })
      },

    //获取关联采购单
    remoteMethod3(query){
      if (query !== '') {
        this.orderLoading = true;
        suggestOrderSn({keywords:query,orderType:this.sendForm.orderType}).then((res)=>{
          this.purchaseOrderList = res;
          this.orderLoading = false;
        })
      } else {
        this.purchaseOrderList = [];
        this.orderLoading = false;
      }
    },

    //切换关联合同
    changeOrderId(val){
      purchaseGoodsDetail({orderId:val,orderType:this.sendForm.orderType}).then((res)=>{
          this.sendForm.detailData = [];
          res.detailList.forEach((el)=>{
            this.sendForm.detailData.push({
              detailId:el.detailId,
              goodsName : el.goodsName,
              goodsSn   : el.goodsSn,
              goodsNum  : el.goodsNum,
              goodsWeight:'',
              planNum:'',
              isHasTray:false,
              goodsRemark:'',
            })
          });
          // this.sendForm.supplierId = res.supplierId;
          this.sendForm.supplierName = res.supplierName;
          this.sendForm.fromCompany = res.fromCompany;
          console.log("this.sendForm",this.sendForm)
      })
    },

      //显示增加仓库弹窗
      showDialog5(){
          this.$refs.warehouseInfo.showDialog('add',null);
      },
      //仓库列表
      getWarehouseList(keywords,warehouseId){
        warehouseListPlan({keywords:keywords}).then((res)=>{
          this.options2 = res;
          this.btnLoading5 = false;
          if(warehouseId){
            this.changeWarehouseId(keywords);
            this.sendForm.takeWarehouse = keywords
          }
        })
      },

      //搜索仓库
      remoteMethod2(query) {
        if (query !== '') {
          this.loading2 = true;
          warehouseListPlan({keywords:query}).then((res)=>{
            this.options2 = res;
            this.loading2 = false;
          })
        } else {
          this.options = [];
          this.loading2 = false;
        }
      },

      changeWarehouseId(val){
        let curWarehouse = this.options2.find((el)=>{
          return el.warehouseName == val
        });
        this.curWarehouse = JSON.parse(JSON.stringify(curWarehouse));
        if(curWarehouse.warehouseId){
          this.sendForm.contactName  = this.curWarehouse.contactName;
          this.sendForm.contactMobile = this.curWarehouse.contactMobile;
          this.sendForm.takeAddress = this.curWarehouse.warehouseAddress;
          this.sendForm.takeNote = this.curWarehouse.takeNote;
        }else{
          this.sendForm = JSON.parse(JSON.stringify(defaultSendForm));
        }
      },




    //显示安排提货
    showDialog2(list){
      this.dialogVisible2 = true;
      this.sendForm = JSON.parse(JSON.stringify(defaultSendForm));
      this.getShckList();
    },

    //关闭安排提货
    handleClose2(){
      this.dialogVisible2 = false;
      this.$refs.sendForm.clearValidate();
    },

    //提交安排提货
    handleConfirm2(){
      if(this.sendForm.detailData.length == 0){
        this.$message({
          type: 'info',
          message: '请添加商品！'
        });
        return false
      }
      this.$refs['sendForm'].validate((valid) => {
        if (valid) {
          this.btnLoading2 = true;
          let pa = JSON.parse(JSON.stringify(this.sendForm));
          pa.detailData = [];
          this.sendForm.detailData.forEach((el)=>{
            pa.detailData.push({
              detailId  : el.detailId,
              goodsKingId : el.goodsKingId,
              planNum   : el.planNum, //提货数量
              goodsWeight : el.goodsWeight, //包装重量
              isHasTray : el.isHasTray ? 1 : 0, //是否含托(1是，0否)
              goodsRemark:el.goodsRemark,
            })
          })
          pa.isNeedDriverUnload = pa.isNeedDriverUnload ? 1 : 0
          planPurchaseGoods(pa).then(()=>{
            this.btnLoading2 = false;
            this.dialogVisible2 = false;
              this.$emit('handleConfirmPums')
          }).catch(()=>{
            this.btnLoading2 = false;
          })
        }
      })
    },

  },
}
</script>

<style scoped lang="scss">

</style>
